/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: RechargeCoinActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.RechargeCoinPresenter;
import io.bhex.app.account.viewhandler.ChainTypeViewController;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.ChainType;
import io.bhex.sdk.socket.Base64;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.sdk.trade.bean.CoinAddressBean;


public class RechargeCoinActivity extends BaseActivity<RechargeCoinPresenter, RechargeCoinPresenter.RechargeCoinUI> implements RechargeCoinPresenter.RechargeCoinUI, View.OnClickListener {
    private AssetListResponse.BalanceBean assetItemBean;
    private CoinAddressBean currentAddressBean;
    private TopBar topBar;
    private TextView chainsTitle;
    private RecyclerView chainTypeRV;
    private String selectChainType="";
    private List<String> tips = new ArrayList<>();  //提示

    @Override
    protected int getContentView() {
        return R.layout.activity_recharge_coin_layout;
    }

    @Override
    protected RechargeCoinPresenter createPresenter() {
        return new RechargeCoinPresenter();
    }

    @Override
    protected RechargeCoinPresenter.RechargeCoinUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        topBar = viewFinder.find(R.id.topBar);
        topBar.setLeftImg(R.mipmap.icon_close);
        ShadowDrawable.setShadow(viewFinder.find(R.id.selectTokenRela));
        if (intent != null) {
            assetItemBean = (AssetListResponse.BalanceBean) intent.getSerializableExtra(AppData.INTENT.KEY_ASSET);
            if (assetItemBean != null) {
                String tokenName = "";
                if(!TextUtils.isEmpty(assetItemBean.getTokenFullName()))
                    tokenName = assetItemBean.getTokenFullName();
                else if(!TextUtils.isEmpty(assetItemBean.getTokenName()))
                    tokenName = assetItemBean.getTokenName();
                else if(!TextUtils.isEmpty(assetItemBean.getTokenId()))
                    tokenName = assetItemBean.getTokenId();

//                String iconUrl = assetItemBean.getIconUrl();
//                if (!TextUtils.isEmpty(iconUrl)) {
//                    ImageView icon = viewFinder.imageView(R.id.coin_icon);
//                    Glide.with(this).load(iconUrl).into(icon);
//                }
                viewFinder.textView(R.id.asset_token_fullname).setText(tokenName);
                viewFinder.textView(R.id.asset_token).setText(assetItemBean.getTokenName());


//                String rechargeTipContent = getString(R.string.string_recharge_address_tip, tokenName);
//                SpannableStringBuilder builder = new SpannableStringBuilder(rechargeTipContent);
//                ForegroundColorSpan orangeColor = new ForegroundColorSpan(getResources().getColor(R.color.orange));
//                int start = getString(R.string.string_recharge_address_tip).indexOf("%s");
//                int end = start + tokenName.length();
//                builder.setSpan(orangeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                viewFinder.textView(R.id.recharge_address_tip).setText(builder);

                topBar.setTitle(assetItemBean.getTokenName() + getString(R.string.title_recharge_coin));
                initChainTypeChoice(assetItemBean.getTokenId());

            }
        }

//        ShadowDrawable.setShadow(viewFinder.find(R.id.token_copy));
//        ShadowDrawable.setShadow(viewFinder.find(R.id.tag_copy));

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            resetView();
            assetItemBean = (AssetListResponse.BalanceBean) intent.getSerializableExtra(AppData.INTENT.KEY_ASSET);
            if (assetItemBean != null) {
                String tokenName = "";
                if(!TextUtils.isEmpty(assetItemBean.getTokenFullName()))
                    tokenName = assetItemBean.getTokenFullName();
                else if(!TextUtils.isEmpty(assetItemBean.getTokenName()))
                    tokenName = assetItemBean.getTokenName();
                else if(!TextUtils.isEmpty(assetItemBean.getTokenId()))
                    tokenName = assetItemBean.getTokenId();

//                String iconUrl = assetItemBean.getIconUrl();
//                if (!TextUtils.isEmpty(iconUrl)) {
//                    ImageView icon = viewFinder.imageView(R.id.coin_icon);
//                    Glide.with(this).load(iconUrl).into(icon);
//                }
                viewFinder.textView(R.id.asset_token_fullname).setText(tokenName);
                viewFinder.textView(R.id.asset_token).setText(assetItemBean.getTokenName());


//                String rechargeTipContent = getString(R.string.string_recharge_address_tip, tokenName);
//                SpannableStringBuilder builder = new SpannableStringBuilder(rechargeTipContent);
//                ForegroundColorSpan orangeColor = new ForegroundColorSpan(getResources().getColor(R.color.orange));
//                int start = getString(R.string.string_recharge_address_tip).indexOf("%s");
//                int end = start + tokenName.length();
//                builder.setSpan(orangeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                viewFinder.textView(R.id.recharge_address_tip).setText(builder);

                topBar.setTitle(assetItemBean.getTokenName() + getString(R.string.title_recharge_coin));
                initChainTypeChoice(assetItemBean.getTokenId());

            }
        }
    }

    /**
     * 初始化-链路类型选择
     * @param tokenId
     */
    private void initChainTypeChoice(final String tokenId) {
        chainsTitle = viewFinder.textView(R.id.chainsTitle);
        chainTypeRV = viewFinder.find(R.id.chainTypeRV);
        List<io.bhex.sdk.quote.bean.ChainType> chainTypes = SymbolDataManager.GetInstance().getTokenChainTypesByTokenId(tokenId);
        if (chainTypes != null&&chainTypes.size()>0) {
            //充币默认类型设置
            boolean isSetSelected = false;
            for (ChainType chainType : chainTypes) {
                if (!isSetSelected && chainType.isAllowDeposit()) {
                    chainType.setSelect(true);
                    isSetSelected = true;
                    selectChainType = chainType.getChainType();
                }else{
                    chainType.setSelect(false);
                }
            }
            chainsTitle.setVisibility(View.VISIBLE);
            chainTypeRV.setVisibility(View.VISIBLE);
            ChainTypeViewController.getInstance().showChainTypesGrid(this,chainTypes, chainTypeRV,1, new ChainTypeViewController.ChainTypeSelectListener() {
                @Override
                public void onItemSelect(ChainType selectChain) {
                    //切换链路
//                    ToastUtils.showShort(selectChain.getChainType());
                    resetView();
                    selectChainType = selectChain.getChainType();
                    getPresenter().getRechargeAddress(tokenId,selectChainType);
                }
            });
        }else{
            chainsTitle.setVisibility(View.GONE);
            chainTypeRV.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (assetItemBean != null) {
            if (!NetWorkStatus.isConnected(this)) {
                ToastUtils.showShort(this, getResources().getString(R.string.hint_network_not_connect));
                return;
            }
            getPresenter().getRechargeAddress(assetItemBean.getTokenId(),selectChainType);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.selectTokenRela).setOnClickListener(this);
        viewFinder.find(R.id.token_copy).setOnClickListener(this);
        viewFinder.find(R.id.save_qrcode_image).setOnClickListener(this);
        viewFinder.find(R.id.token_qrcode).setOnClickListener(this);
        viewFinder.find(R.id.tag_copy).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.selectTokenRela:
                IntentUtils.goTokenList(this,true);
                break;
            case R.id.token_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.token_address).getText().toString());
                break;
            case R.id.tag_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.tag_content).getText().toString());
                break;
            case R.id.token_qrcode:
            case R.id.save_qrcode_image:

                if (currentAddressBean != null) {
                    try {
                        byte[] qrCodeByte = Base64.decode(currentAddressBean.getQrcode());
                        //TODO 保存到相册

                        ImageUtils.saveImageToGallery(this, ImageUtils.Bytes2Bimap(qrCodeByte));
                        ToastUtils.showShort(this, getString(R.string.string_save_success));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void showCoinAddress(CoinAddressBean response) {
        currentAddressBean = response;
        viewFinder.textView(R.id.token_address).setText(response.getAddress());
        ImageView qrCode = viewFinder.imageView(R.id.token_qrcode);
        if (!TextUtils.isEmpty(response.getQrcode())) {
            try {
                byte[] qrCodeByte = Base64.decode(response.getQrcode(), Base64.DECODE);
                Glide.with(this).load(qrCodeByte).into(qrCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        viewFinder.textView(R.id.with_tips_c).setText(getString(R.string.string_with_tips_c,response.getMinQuantity()));
//        viewFinder.textView(R.id.deposit_tips).setText(getString(R.string.string_deposit_tips, assetItemBean.getTokenName(), assetItemBean.getTokenName(), response.getMinQuantity(),assetItemBean.getTokenName(),assetItemBean.getTokenName(),response.getRequiredConfirmNum()+""));

        tips.clear();
        tips.add(getString(R.string.string_recharge_coin_tips_a,assetItemBean.getTokenName(), assetItemBean.getTokenName()));
        tips.add(getString(R.string.string_recharge_coin_tips_b,assetItemBean.getTokenName(),response.getRequiredConfirmNum()+"", response.getCanWithdrawConfirmNum()+""));
        tips.add(getString(R.string.string_recharge_coin_tips_c));
        tips.add(getString(R.string.string_recharge_coin_tips_d,response.getMinQuantity(),assetItemBean.getTokenName()));
        if (assetItemBean.getTokenId().equalsIgnoreCase("ETH")) {
            tips.add(getString(R.string.string_recharge_coin_tips_e));
            tips.add(getString(R.string.string_recharge_coin_tips_f));
        }
        tips.add(getString(R.string.string_recharge_coin_tips_g));
        if (assetItemBean.getTokenId().equalsIgnoreCase("ZEC")) {
            tips.add(getString(R.string.string_recharge_coin_tips_h));
        }
        String tokenType = response.getTokenType();
        if (!TextUtils.isEmpty(tokenType)) {
            if (tokenType.equalsIgnoreCase("ERC20_TOKEN")) {
                tips.add(getString(R.string.string_recharge_erc20_coin_tips,assetItemBean.getTokenName()));
            }
        }

        StringBuffer tipsContent = new StringBuffer();
        for (int i = 0; i < tips.size(); i++) {
            int num = i+1;
            tipsContent.append(num+"."+tips.get(i)+"\n");
        }
        viewFinder.textView(R.id.deposit_tips).setText(tipsContent.toString());

        //EOS 特殊处理
        if (response.isNeedAddressTag()) {
            viewFinder.textView(R.id.tag_content).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tag_content).setText(response.getAddressExt());
            viewFinder.find(R.id.tag_copy).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tag_tips).setVisibility(View.VISIBLE);
        }else{
            viewFinder.textView(R.id.tag_content).setVisibility(View.GONE);
            viewFinder.textView(R.id.tag_content).setText("");
            viewFinder.find(R.id.tag_copy).setVisibility(View.GONE);
            viewFinder.textView(R.id.tag_tips).setVisibility(View.GONE);
        }
    }

    public void resetView() {
        viewFinder.textView(R.id.token_address).setText("");
        ImageView qrCode = viewFinder.imageView(R.id.token_qrcode);
        qrCode.setImageBitmap(null);
//        viewFinder.textView(R.id.with_tips_c).setText(getString(R.string.string_with_tips_c,response.getMinQuantity()));
        viewFinder.textView(R.id.deposit_tips).setText("");

        //TAG
        viewFinder.textView(R.id.tag_content).setVisibility(View.GONE);
        viewFinder.textView(R.id.tag_content).setText("");
        viewFinder.find(R.id.tag_copy).setVisibility(View.GONE);
        viewFinder.textView(R.id.tag_tips).setVisibility(View.GONE);
    }
}
